package com.xy.servicemanage.db;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.xy.servicemanage.model.Tdatabase;

public class PoolManager {
	private static Map<String, ConnectionPool> poolMap = new HashMap<String, ConnectionPool>();
	static {
		init();
	}

	public static void init() {
		List<Tdatabase> list = getDbConfig();
		for (Tdatabase d : list) {
			ConnectionPool p = new ConnectionPool(d.getDataSourceID(),
					d.getJdbcDriver(), d.getJdbcUrl(), d.getJdbcUser(),
					d.getJdbcPassword(),d.getPoolsize());
//			p.setMaxUseTime(20);
			poolMap.put(d.getDataSourceID(), p);
		}

	}

	public static Connection getConnection(String datasourceID)
			throws Exception {
		return poolMap.get(datasourceID).getConnection();
	}

	private static Properties getJdbcConfig() {
		InputStream is = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream("../config/jdbc.properties");
		Properties p = new Properties();
		try {
			p.load(is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return p;
	}

	private static List<Tdatabase> getDbConfig() {
		List<Tdatabase> ret = new ArrayList<Tdatabase>();

		Properties p = getJdbcConfig();
		try {
			String driver = p.getProperty("jdbc.driverClassName");
			String url = p.getProperty("jdbc.url");
			String user = p.getProperty("jdbc.username");
			String password = p.getProperty("jdbc.password");
			String sql = "select * from t_database";
			Class.forName(driver);
			Connection con = DriverManager.getConnection(url, user, password);
			PreparedStatement ps = con.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				String dataSourceID = rs.getString("dataSourceID");
				String jdbcDriver = rs.getString("jdbcDriver");
				String jdbcUrl = rs.getString("jdbcUrl");
				String jdbcUser = rs.getString("jdbcUser");
				String jdbcPassword = rs.getString("JdbcPassword");
				String bz = rs.getString("bz");
				Tdatabase d = new Tdatabase(dataSourceID, jdbcDriver, jdbcUrl,
						jdbcUser, jdbcPassword,bz);
				ret.add(d);
			}
			rs.close();
			ps.close();
			con.close();

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ret;
	}

}
